#!/usr/bin/env python
# coding=utf-8

import json
import re
import time
import traceback

from aliyunsdkcore import client
from aliyunsdkcore.client import ClientException, ServerException
# instance
from aliyunsdkecs.request.v20140526 import CreateInstanceRequest, DeleteInstanceRequest
from aliyunsdkecs.request.v20140526 import DescribeInstanceAutoRenewAttributeRequest
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest, DescribeInstanceStatusRequest
from aliyunsdkecs.request.v20140526 import DescribeInstanceVncUrlRequest, DescribeUserDataRequest
from aliyunsdkecs.request.v20140526 import ModifyInstanceAttributeRequest, ModifyInstanceVncPasswdRequest
from aliyunsdkecs.request.v20140526 import ModifyInstanceAutoReleaseTimeRequest, RebootInstanceRequest
from aliyunsdkecs.request.v20140526 import ModifyInstanceAutoRenewAttributeRequest, StopInstanceRequest
from aliyunsdkecs.request.v20140526 import ModifyInstanceVpcAttributeRequest, ModifyInstanceNetworkSpecRequest
from aliyunsdkecs.request.v20140526 import RenewInstanceRequest, StartInstanceRequest
from aliyunsdkecs.request.v20140526 import DescribeRegionsRequest, DescribeZonesRequest
# network
from aliyunsdkecs.request.v20140526 import AllocateEipAddressRequest
from aliyunsdkecs.request.v20140526 import AllocatePublicIpAddressRequest
# disk
from aliyunsdkecs.request.v20140526 import CreateDiskRequest, DeleteDiskRequest, DescribeDisksRequest
from aliyunsdkecs.request.v20140526 import ModifyDiskAttributeRequest, AttachDiskRequest, DetachDiskRequest
from aliyunsdkecs.request.v20140526 import ReInitDiskRequest, ResetDiskRequest, ReplaceSystemDiskRequest
from aliyunsdkecs.request.v20140526 import ResizeDiskRequest
# image
from aliyunsdkecs.request.v20140526 import CreateImageRequest, DeleteImageRequest, DescribeImagesRequest
from aliyunsdkecs.request.v20140526 import DescribeImageSharePermissionRequest, ModifyImageAttributeRequest
from aliyunsdkecs.request.v20140526 import ModifyImageSharePermissionRequest, CopyImageRequest
from aliyunsdkecs.request.v20140526 import CancelCopyImageRequest, ImportImageRequest
# snapshot
from aliyunsdkecs.request.v20140526 import CreateSnapshotRequest, DeleteSnapshotRequest, ModifySnapshotAttributeRequest
from aliyunsdkecs.request.v20140526 import CreateAutoSnapshotPolicyRequest, DeleteAutoSnapshotPolicyRequest
from aliyunsdkecs.request.v20140526 import ModifyAutoSnapshotPolicyExRequest, DescribeSnapshotsRequest
from aliyunsdkecs.request.v20140526 import DescribeAutoSnapshotPolicyRequest, DescribeAutoSnapshotPolicyExRequest
from aliyunsdkecs.request.v20140526 import ApplyAutoSnapshotPolicyRequest, CancelAutoSnapshotPolicyRequest
# keypairs
from aliyunsdkecs.request.v20140526 import CreateKeyPairRequest, DescribeKeyPairsRequest, DeleteKeyPairsRequest
from aliyunsdkecs.request.v20140526 import ImportKeyPairRequest, AttachKeyPairRequest, DetachKeyPairRequest
# rds
from aliyunsdkrds.request.v20140815 import CreateDBInstanceRequest, DeleteDBInstanceRequest, RestartDBInstanceRequest
from aliyunsdkrds.request.v20140815 import DescribeDBInstanceAttributeRequest, DescribeDBInstancesRequest
from aliyunsdkrds.request.v20140815 import ModifyDBInstanceSpecRequest, ModifyDBInstancePayTypeRequest
from aliyunsdkrds.request.v20140815 import ModifyInstanceAutoRenewalAttributeRequest, AllocateInstancePublicConnectionRequest
from aliyunsdkrds.request.v20140815 import ReleaseInstancePublicConnectionRequest, SwitchDBInstanceNetTypeRequest
from aliyunsdkrds.request.v20140815 import DescribeDBInstanceNetInfoRequest, ModifyDBInstanceConnectionStringRequest
from aliyunsdkrds.request.v20140815 import ModifyDBInstanceConnectionModeRequest, ModifyDBInstanceNetworkTypeRequest
from aliyunsdkrds.request.v20140815 import DescribeDBInstanceIPArrayListRequest, ModifySecurityIpsRequest
from aliyunsdkrds.request.v20140815 import DescribeRegionsRequest, DescribeDBInstanceHAConfigRequest
from aliyunsdkrds.request.v20140815 import MigrateToOtherZoneRequest, PurgeDBInstanceLogRequest
from aliyunsdkrds.request.v20140815 import UpgradeDBInstanceEngineVersionRequest, ModifyDBInstanceDescriptionRequest
from aliyunsdkrds.request.v20140815 import ModifyDBInstanceMaintainTimeRequest, ModifyDBInstanceHAConfigRequest
from aliyunsdkrds.request.v20140815 import SwitchDBInstanceHARequest, CreateReadOnlyDBInstanceRequest
from aliyunsdkrds.request.v20140815 import DescribeDBInstanceSSLRequest, ModifyDBInstanceSSLRequest
from aliyunsdkrds.request.v20140815 import DescribeDBInstanceTDERequest, ModifyDBInstanceTDERequest
from aliyunsdkrds.request.v20140815 import ModifyDBInstanceNetworkExpireTimeRequest, CreateDatabaseRequest
from aliyunsdkrds.request.v20140815 import DeleteDatabaseRequest, DescribeDatabasesRequest, ModifyDBDescriptionRequest
from aliyunsdkrds.request.v20140815 import CreateBackupRequest, CloneDBInstanceRequest, DescribeBackupsRequest
from aliyunsdkrds.request.v20140815 import CreateTempDBInstanceRequest, DescribeBackupPolicyRequest
from aliyunsdkrds.request.v20140815 import ModifyBackupPolicyRequest, RestoreDBInstanceRequest, DeleteBackupRequest
from aliyunsdkrds.request.v20140815 import AllocateReadWriteSplittingConnectionRequest, CalculateDBInstanceWeightRequest
from aliyunsdkrds.request.v20140815 import ModifyReadWriteSplittingConnectionRequest, ReleaseReadWriteSplittingConnectionRequest
from aliyunsdkrds.request.v20140815 import CreateAccountRequest, DeleteAccountRequest, DescribeAccountsRequest
from aliyunsdkrds.request.v20140815 import GrantAccountPrivilegeRequest, RevokeAccountPrivilegeRequest
from aliyunsdkrds.request.v20140815 import ModifyAccountDescriptionRequest, ResetAccountPasswordRequest, ResetAccountForPGRequest
from aliyunsdkrds.request.v20140815 import DescribeSlowLogsRequest, DescribeSlowLogRecordsRequest, DescribeErrorLogsRequest
from aliyunsdkrds.request.v20140815 import DescribeBinlogFilesRequest, DescribeSQLCollectorPolicyRequest
from aliyunsdkrds.request.v20140815 import ModifySQLCollectorPolicyRequest, DescribeSQLLogRecordsRequest
from aliyunsdkrds.request.v20140815 import DescribeSQLLogFilesRequest, DescribeResourceUsageRequest
from aliyunsdkrds.request.v20140815 import DescribeDBInstancePerformanceRequest, DescribeDBInstanceMonitorRequest
from aliyunsdkrds.request.v20140815 import ModifyDBInstanceMonitorRequest, DescribeParameterTemplatesRequest
from aliyunsdkrds.request.v20140815 import DescribeParametersRequest, ModifyParameterRequest, CreateUploadPathForSQLServerRequest
from aliyunsdkrds.request.v20140815 import DescribeFilesForSQLServerRequest, DescribeImportsForSQLServerRequest
from aliyunsdkrds.request.v20140815 import ImportDatabaseBetweenInstancesRequest, CancelImportRequest
from aliyunsdkrds.request.v20140815 import DescribeSQLLogReportsRequest, DescribeOptimizeAdviceOnMissIndexRequest
from aliyunsdkrds.request.v20140815 import AddTagsToResourceRequest, DescribeTagsRequest, RemoveTagsFromResourceRequest
# mns
from aliyun_product_operation_mns import ALiYunMnsOperation
# eni
from aliyunsdkecs.request.v20140526 import CreateNetworkInterfaceRequest, AttachNetworkInterfaceRequest, \
                                            DescribeNetworkInterfacesRequest, DetachNetworkInterfaceRequest, \
                                            DeleteNetworkInterfaceRequest, ModifyNetworkInterfaceAttributeRequest

from log import debug, info, warn, error
from utils import Singleton

def _get_exception_response_id(msg):
    import re
    response_id = ""
    pattern = re.compile("[\w|\d]{8}-[\w|\d|-]+")
    res = pattern.findall(msg)
    if res:
        response_id = res[0]
    else:
        warn("Failed to find response id in exception message.")
    return response_id

class ALiYunEniOperation(Singleton):

    def __init__(self, ak, secret, region_id):
        self.ak = ak
        self.secret = secret
        self.region_id = region_id
        self.clt = client.AcsClient(ak, secret, region_id)

    def CreateNetworkInterface(self, **kwargs):
        res = None
        try:
            req = CreateNetworkInterfaceRequest.CreateNetworkInterfaceRequest()
            req.set_accept_format("json")

            req.set_VSwitchId(kwargs["VSwitchId"])

            req.set_SecurityGroupId(kwargs["SecurityGroupId"])

            if "PrimaryIpAddress" in kwargs:
                req.set_PrimaryIpAddress(kwargs["PrimaryIpAddress"])

            if "NetworkInterfaceName" in kwargs:
                req.set_NetworkInterfaceName(kwargs["NetworkInterfaceName"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            if "ClientToken" in kwargs:
                req.set_ClientToken(kwargs["ClientToken"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateNetworkInterface with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                if "ClientToken" not in kwargs:
                    kwargs["ClientToken"] = "%d" % (time.time())
                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute CreateNetworkInterface ...")
                    res = self.CreateNetworkInterface(**kwargs)
                    if res["StatusCode"] == "200":
                        break
                    time.sleep(5)
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateNetworkInterface with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def AttachNetworkInterface(self, **kwargs):
        res = None
        try:
            req = AttachNetworkInterfaceRequest.AttachNetworkInterfaceRequest()
            req.set_accept_format("json")

            req.set_NetworkInterfaceId(kwargs["NetworkInterfaceId"])

            req.set_InstanceId(kwargs["InstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute AttachNetworkInterface with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeNetworkInterfaces(self, **kwargs):
        res = None
        try:
            req = DescribeNetworkInterfacesRequest.DescribeNetworkInterfacesRequest()
            req.set_accept_format("json")

            if "VSwitchId" in kwargs:
                req.set_VSwitchId(kwargs["VSwitchId"])

            if "PrimaryIpAddress" in kwargs:
                req.set_PrimaryIpAddress(kwargs["PrimaryIpAddress"])

            if "SecurityGroupId" in kwargs:
                req.set_SecurityGroupId(kwargs["SecurityGroupId"])

            if "NetworkInterfaceName" in kwargs:
                req.set_NetworkInterfaceName(kwargs["NetworkInterfaceName"])

            if "Type" in kwargs:
                req.set_Type(kwargs["Type"])

            if "InstanceId" in kwargs:
                req.set_InstanceId(kwargs["InstanceId"])

            if "NetworkInterfaceIds" in kwargs:
                # list
                req.set_NetworkInterfaceIds(kwargs["NetworkInterfaceIds"])

            if "PageNumber" in kwargs:
                # int
                req.set_PageNumber(kwargs["PageNumber"])

            if "PageSize" in kwargs:
                #int
                req.set_PageSize(kwargs["PageSize"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeNetworkInterfaces with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DetachNetworkInterface(self, **kwargs):
        res = None
        try:
            req = DetachNetworkInterfaceRequest.DetachNetworkInterfaceRequest()
            req.set_accept_format("json")

            req.set_NetworkInterfaceId(kwargs["NetworkInterfaceId"])

            req.set_InstanceId(kwargs["InstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DetachNetworkInterface with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteNetworkInterface(self, **kwargs):
        res = None
        try:
            req = DeleteNetworkInterfaceRequest.DeleteNetworkInterfaceRequest()
            req.set_accept_format("json")

            req.set_NetworkInterfaceId(kwargs["NetworkInterfaceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteNetworkInterface with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute DeleteNetworkInterface ...")
                    res = self.DeleteNetworkInterface(**kwargs)
                    if res["StatusCode"] == "200":
                        break
                    time.sleep(5)

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteNetworkInterface with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyNetworkInterfaceAttribute(self, **kwargs):
        res = None
        try:
            req = ModifyNetworkInterfaceAttributeRequest.ModifyNetworkInterfaceAttributeRequest()
            req.set_accept_format("json")

            req.set_NetworkInterfaceId(kwargs["NetworkInterfaceId"])

            if "SecurityGroupIds" in kwargs:
                req.set_SecurityGroupIds(kwargs["SecurityGroupIds"])

            if "NetworkInterfaceName" in kwargs:
                req.set_NetworkInterfaceName(kwargs["NetworkInterfaceName"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyNetworkInterfaceAttribute with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

class ALiYunInstanceOperation(Singleton):

    def __init__(self, ak, secret, region_id):
        self.ak = ak
        self.secret = secret
        self.region_id = region_id
        self.clt = client.AcsClient(ak, secret, region_id)

    def CreateInstance(self, **kwargs):
        res = None
        try:
            req = CreateInstanceRequest.CreateInstanceRequest()
            req.set_accept_format("json")
            # because the region is was setted when initialize the client
            # so we do not set it again.
            # req.set_RegionId(kwargs["RegionId"])

            req.set_ImageId(kwargs["ImageId"])
            req.set_InstanceType(kwargs["InstanceType"])

            if "SecurityGroupId" in kwargs:
                req.set_SecurityGroupId(kwargs["SecurityGroupId"])

            if "InstanceName" in kwargs:
                req.set_InstanceName(kwargs["InstanceName"])

            if "InternetChargeType" in kwargs:
                req.set_InternetChargeType(kwargs["InternetChargeType"])

            if "AutoRenew" in kwargs:
                # bool
                req.set_AutoRenew(kwargs["AutoRenew"])

            if "AutoRenewPeriod" in kwargs:
                # int
                req.set_AutoRenewPeriod(kwargs["AutoRenewPeriod"])

            if "InternetMaxBandwidthIn" in kwargs:
                # int
                req.set_InternetMaxBandwidthIn(kwargs["InternetMaxBandwidthIn"])

            if "InternetMaxBandwidthOut" in kwargs:
                # int
                req.set_InternetMaxBandwidthOut(kwargs["InternetMaxBandwidthOut"])

            if "HostName" in kwargs:
                req.set_HostName(kwargs["HostName"])

            if "Password" in kwargs:
                req.set_Password(kwargs["Password"])

            if "DeploymentSetId" in kwargs:
                req.set_DeploymentSetId(kwargs["DeploymentSetId"])

            if "ZoneId" in kwargs:
                req.set_ZoneId(kwargs["ZoneId"])

            if "ClusterId" in kwargs:
                req.set_ClusterId(kwargs["ClusterId"])

            if "ClientToken" in kwargs:
                req.set_ClientToken(kwargs["ClientToken"])

            if "VlanId" in kwargs:
                req.set_VlanId(kwargs["VlanId"])

            if "InnerIpAddress" in kwargs:
                req.set_InnerIpAddress(kwargs["InnerIpAddress"])

            if "SystemDiskSize" in kwargs:
                # int
                req.set_SystemDiskSize(kwargs["SystemDiskSize"])

            if "SystemDiskCategory" in kwargs:
                req.set_SystemDiskCategory(kwargs["SystemDiskCategory"])

            if "SystemDiskName" in kwargs:
                req.set_SystemDiskDiskName(kwargs["SystemDiskName"])

            if "SystemDiskDescription" in kwargs:
                req.set_SystemDiskDescription(kwargs["SystemDiskDescription"])

            if "NodeControllerId" in kwargs:
                req.set_NodeControllerId(kwargs["NodeControllerId"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            if "VSwitchId" in kwargs:
                req.set_VSwitchId(kwargs["VSwitchId"])

            if "PrivateIpAddress" in kwargs:
                req.set_PrivateIpAddress(kwargs["PrivateIpAddress"])

            if "IoOptimized" in kwargs:
                # bool
                req.set_IoOptimized(kwargs["IoOptimized"])

            if "UseAdditionalService" in kwargs:
                # maybe bool
                req.set_UseAdditionalService(kwargs["UseAdditionalService"])

            if "InstanceChargeType" in kwargs:
                req.set_InstanceChargeType(kwargs["InstanceChargeType"])

            if "Period" in kwargs:
                req.set_Period(kwargs["Period"])

            if "UserData" in kwargs:
                req.set_UserData(kwargs["UserData"])

            if "SpotStrategy" in kwargs:
                req.set_SpotStrategy(kwargs["SpotStrategy"])

            if "KeyPairName" in kwargs:
                req.set_KeyPairName(kwargs["KeyPairName"])

            for k, v in kwargs.items():
                if "DataDisk" in k:
                    req.add_query_param(k, v)
                if "Tag" in k:
                    req.add_query_param(k, v)

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateInstance with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                if "ClientToken" not in kwargs:
                    kwargs["ClientToken"] = "%d" % (time.time())
                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute CreateInstance ...")
                    res = self.CreateInstance(**kwargs)
                    if res["StatusCode"] == "200":
                        break
                    time.sleep(5)
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateInstance with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteInstance(self, **kwargs):
        res = None
        try:
            req = DeleteInstanceRequest.DeleteInstanceRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])

            if "Force" in kwargs:
                req.set_Force(kwargs["Force"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteInstance with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute DeleteInstance ...")
                    res = self.DeleteInstance(**kwargs)
                    if res["StatusCode"] == "200":
                        break
                    time.sleep(5)

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteInstance with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeInstanceAutoRenewAttribute(self, **kwargs):
        res = None
        try:
            req = DescribeInstanceAutoRenewAttributeRequest.DescribeInstanceAutoRenewAttributeRequest()
            req.set_accept_format("json")

            # req.set_RegionId(kwargs["RegionId"])
            req.set_InstanceId(kwargs["InstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeInstanceAutoRenewAttribute with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeInstances(self, **kwargs):
        res = None
        try:
            req = DescribeInstancesRequest.DescribeInstancesRequest()
            req.set_accept_format("json")

            # req.set_RegionId(kwargs["RegionId"])
            if "VpcId" in  kwargs:
                req.set_VpcId(kwargs["VpcId"])

            if "VSwitchId" in kwargs:
                req.set_VSwitchId(kwargs["VSwitchId"])

            if "ZoneId" in kwargs:
                req.set_ZoneId(kwargs["ZoneId"])

            if "InstanceNetworkType" in kwargs:
                req.set_InstanceNetworkType(kwargs["InstanceNetworkType"])

            if "SecurityGroupId" in kwargs:
                req.set_SecurityGroupId(kwargs["SecurityGroupId"])

            if "InstanceIds" in kwargs:
                req.set_InstanceIds(kwargs["InstanceIds"])

            if "PageNumber" in kwargs:
                # int
                req.set_PageNumber(kwargs["PageNumber"])

            if "PageSize" in kwargs:
                # int
                req.set_PageSize(kwargs["PageSize"])

            if "InnerIpAddresses" in kwargs:
                req.set_InnerIpAddresses(kwargs["InnerIpAddresses"])

            if "PrivateIpAddresses" in kwargs:
                req.set_PrivateIpAddresses(kwargs["PrivateIpAddresses"])

            if "PublicIpAddresses" in kwargs:
                req.set_PublicIpAddresses(kwargs["PublicIpAddresses"])

            if "InternetChargeType" in kwargs:
                req.set_InternetChargeType(kwargs["InternetChargeType"])

            if "InstanceName" in kwargs:
                req.set_InstanceName(kwargs["InstanceName"])

            if "ImageId" in kwargs:
                req.set_ImageId(kwargs["ImageId"])

            if "Status" in kwargs:
                req.set_Status(kwargs["Status"])

            if "LockReason" in kwargs:
                req.set_LockReason(kwargs["LockReason"])

            if "DeviceAvailable" in kwargs:
                req.set_DeviceAvailable(kwargs["DeviceAvailable"])

            if "IoOptimized" in kwargs:
                # bool
                req.set_IoOptimized(kwargs["IoOptimized"])

            if "InstanceType" in kwargs:
                req.set_InstanceType(kwargs["InstanceType"])

            if "InstanceTypeFamily" in kwargs:
                req.set_InstanceTypeFamily(kwargs["InstanceTypeFamily"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeInstances with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeInstanceStatus(self, **kwargs):
        res = None
        try:
            req = DescribeInstanceStatusRequest.DescribeInstanceStatusRequest()
            req.set_accept_format("json")

            # req.set_RegionId(kwargs["RegionId"])
            if "ZoneId" in kwargs:
                req.set_ZoneId(kwargs["ZoneId"])

            if "ClusterId" in kwargs:
                req.set_ClusterId(kwargs["ClusterId"])

            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeInstanceStatus with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeInstanceVncUrl(self, **kwargs):
        res = None
        try:
            req = DescribeInstanceVncUrlRequest.DescribeInstanceVncUrlRequest()
            req.set_accept_format("json")

            # req.set_RegionId(kwargs["RegionId"])
            req.set_InstanceId(kwargs["InstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeInstanceVncUrl with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeUserData(self, **kwargs):
        res = None
        try:
            req = DescribeUserDataRequest.DescribeUserDataRequest()
            req.set_accept_format("json")

            # req.set_RegionId(kwargs["RegionId"])
            req.set_InstanceId(kwargs["InstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeUserData with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeRegions(self, **kwargs):
        res = None
        try:
            req = DescribeRegionsRequest.DescribeRegionsRequest()
            req.set_accept_format("json")

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeRegions with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeZones(self, **kwargs):
        res = None
        try:
            req = DescribeZonesRequest.DescribeZonesRequest()
            req.set_accept_format("json")

            # if "InstanceChargeType" in kwargs:
            #     req.set_InstanceChargeType(kwargs["InstanceChargeType"])
            # if "SpotStrategy" in kwargs:
            #     req.set_SpotStrategy(kwargs["SpotStrategy"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeZones with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyInstanceAttribute(self, **kwargs):
        res = None
        try:
            req = ModifyInstanceAttributeRequest.ModifyInstanceAttributeRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])

            if "Password" in kwargs:
                req.set_Password(kwargs["Password"])

            if "HostName" in kwargs:
                req.set_HostName(kwargs["HostName"])

            if "InstanceName" in kwargs:
                req.set_InstanceName(kwargs["InstanceName"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            if "UserData" in kwargs:
                req.set_UserData(kwargs["UserData"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyInstanceAttribute with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyInstanceAutoReleaseTime(self, **kwargs):
        res = None
        try:
            req = ModifyInstanceAutoReleaseTimeRequest.ModifyInstanceAutoReleaseTimeRequest()
            req.set_accept_format("json")

            # req.set_RegionId(kwargs["RegionId"])
            req.set_InstanceId(kwargs["InstanceId"])

            if "AutoReleaseTime" in kwargs:
                req.set_AutoReleaseTime(kwargs["AutoReleaseTime"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyInstanceAutoReleaseTime with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyInstanceAutoRenewAttribute(self, **kwargs):
        res = None
        try:
            req = ModifyInstanceAutoRenewAttributeRequest.ModifyInstanceAutoRenewAttributeRequest()
            req.set_accept_format("json")

            # req.set_RegionId(kwargs["RegionId"])
            req.set_InstanceId(kwargs["InstanceId"])

            if "Duration" in kwargs:
                # int
                req.set_Duration(kwargs["Duration"])

            if "AutoRenew" in kwargs:
                # bool
                req.set_AutoRenew(kwargs["AutoRenew"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyInstanceAutoRenewAttribute with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyInstanceVncPasswd(self, **kwargs):
        res = None
        try:
            req = ModifyInstanceVncPasswdRequest.ModifyInstanceVncPasswdRequest()
            req.set_accept_format("json")

            # req.set_RegionId(kwargs["RegionId"])
            req.set_InstanceId(kwargs["InstanceId"])
            req.set_VncPassword(kwargs["VncPassword"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyInstanceVncPasswd with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyInstanceVpcAttribute(self, **kwargs):
        res = None
        try:
            req = ModifyInstanceVpcAttributeRequest.ModifyInstanceVpcAttributeRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])
            req.set_VSwitchId(kwargs["VSwitchId"])

            if "PrivateIpAddress" in kwargs:
                req.set_PrivateIpAddress(kwargs["PrivateIpAddress"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyInstanceVpcAttribute with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyInstanceNetworkSpec(self, **kwargs):
        res = None
        try:
            req = ModifyInstanceNetworkSpecRequest.ModifyInstanceNetworkSpecRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])

            if "InternetMaxBandwidthOut" in kwargs:
                req.set_InternetMaxBandwidthOut(kwargs["InternetMaxBandwidthOut"])
            if "InternetMaxBandwidthIn" in kwargs:
                req.set_InternetMaxBandwidthIn(kwargs["InternetMaxBandwidthIn"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyInstanceNetworkSpec with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def RebootInstance(self,**kwargs):
        res = None
        try:
            req = RebootInstanceRequest.RebootInstanceRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])

            if "ForceStop:" in kwargs:
                # bool
                req.set_ForceStop(kwargs["ForceStop"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute RebootInstance with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def RenewInstance(self, **kwargs):
        res = None
        try:
            req = RenewInstanceRequest.RenewInstanceRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])
            req.set_Period(kwargs["Period"])
            # if "ClientToken" in kwargs:
            #     req.set_ClientToken(kwargs["ClientToken"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute RenewInstance with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def StartInstance(self, **kwargs):
        res = None
        try:
            req = StartInstanceRequest.StartInstanceRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute StartInstance with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def StopInstance(self, **kwargs):
        res = None
        try:
            req = StopInstanceRequest.StopInstanceRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])

            if "ConfirmStop" in kwargs:
                req.set_ConfirmStop(kwargs["ConfirmStop"])

            if "ForceStop" in kwargs:
                req.set_ForceStop(kwargs["ForceStop"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute StopInstance with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def AllocatePublicIpAddress(self, **kwargs):
        res = None
        try:
            req = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute AllocatePublicIpAddress with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

class ALiYunDiskOperation(Singleton):

    def __init__(self, ak, secret, region_id):
        self.ak = ak
        self.secret = secret
        self.region_id = region_id
        self.clt = client.AcsClient(ak, secret, region_id)

    def CreateDisk(self, **kwargs):
        res = None
        try:
            req = CreateDiskRequest.CreateDiskRequest()
            req.set_accept_format("json")

            req.set_ZoneId(kwargs["ZoneId"])

            if "DiskName" in kwargs:
                req.set_DiskName(kwargs["DiskName"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            if "DiskCategory" in kwargs:
                req.set_DiskCategory(kwargs["DiskCategory"])

            if "Size" in kwargs:
                req.set_Size(kwargs["Size"])

            if "SnapshotId" in kwargs:
                req.set_SnapshotId(kwargs["SnapshotId"])

            if "ClientToken" in kwargs:
                req.set_ClientToken(kwargs["ClientToken"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateDisk with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                if "ClientToken" not in kwargs:
                    kwargs["ClientToken"] = "%d" % (time.time())
                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute CreateDisk ...")
                    res = self.CreateDisk(**kwargs)
                    if res["StatusCode"] == "200":
                        break

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateDisk with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteDisk(self, **kwargs):
        res = None
        try:
            req = DeleteDiskRequest.DeleteDiskRequest()
            req.set_accept_format("json")

            req.set_DiskId(kwargs["DiskId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteDisk with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute DeleteDisk ...")
                    res = self.DeleteDisk(**kwargs)
                    if res["StatusCode"] == "200":
                        break

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteDisk with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDisks(self, **kwargs):
        res = None
        try:
            req = DescribeDisksRequest.DescribeDisksRequest()
            req.set_accept_format("json")

            if "ZoneId" in kwargs:
                req.set_ZoneId(kwargs["ZoneId"])

            if "DiskIds" in kwargs:
                req.set_DiskIds(kwargs["DiskIds"])

            if "InstanceId" in kwargs:
                req.set_InstanceId(kwargs["InstanceId"])

            if "DiskName" in kwargs:
                req.set_DiskName(kwargs["DiskName"])

            if "DiskType" in kwargs:
                req.set_DiskType(kwargs["DiskType"])

            if "Category" in kwargs:
                req.set_Category(kwargs["Category"])

            if "Status" in kwargs:
                req.set_Status(kwargs["Status"])

            if "SnapshotId" in kwargs:
                req.set_SnapshotId(kwargs["SnapshotId"])

            if "Portable" in kwargs:
                # bool
                req.set_Portable(kwargs["Portable"])

            if "DeleteWithInstance" in kwargs:
                # bool
                req.set_DeleteWithInstance(kwargs["DeleteWithInstance"])

            if "DeleteAutoSnapshot" in kwargs:
                # bool
                req.set_DeleteAutoSnapshot(kwargs["DeleteAutoSnapshot"])

            if "PageNumber" in kwargs:
                # int
                req.set_PageNumber(kwargs["PageNumber"])

            if "PageSize" in kwargs:
                # int
                req.set_PageSize(kwargs["PageSize"])

            if "AutoSnapshotPolicyId" in kwargs:
                req.set_AutoSnapshotPolicyId(kwargs["AutoSnapshotPolicyId"])

            if "EnableAutoSnapshot" in kwargs:
                req.set_EnableAutoSnapshot(kwargs["EnableAutoSnapshot"])

            if "EnableAutomatedSnapshotPolicy" in kwargs:
                req.set_EnableAutomatedSnapshotPolicy(kwargs["EnableAutomatedSnapshotPolicy"])

            if "DiskChargeType" in kwargs:
                req.set_DiskChargeType(kwargs["DiskChargeType"])

            if "LockReason" in kwargs:
                req.set_LockReason(kwargs["LockReason"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDisks with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDiskAttribute(self, **kwargs):
        res = None
        try:
            req = ModifyDiskAttributeRequest.ModifyDiskAttributeRequest()
            req.set_accept_format("json")

            req.set_DiskId(kwargs["DiskId"])

            if "DiskName" in kwargs:
                req.set_DiskName(kwargs["DiskName"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            if "DeleteWithInstance" in kwargs:
                # bool
                req.set_DeleteWithInstance(kwargs["DeleteWithInstance"])

            if "DeleteAutoSnapshot" in kwargs:
                # bool
                req.set_DeleteAutoSnapshot(kwargs["DeleteAutoSnapshot"])

            if "EnableAutoSnapshot" in kwargs:
                # bool
                req.set_EnableAutoSnapshot(kwargs["EnableAutoSnapshot"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDiskAttribute with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    # The following are operations
    def AttachDisk(self, **kwargs):
        res = None
        try:
            req = AttachDiskRequest.AttachDiskRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])
            req.set_DiskId(kwargs["DiskId"])

            if "Device" in kwargs:
                req.set_Device(kwargs["Device"])

            if "DeleteWithInstance" in kwargs:
                req.set_DeleteWithInstance(kwargs["DeleteWithInstance"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute AttachDisk with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DetachDisk(self, **kwargs):
        res = None
        try:
            req = DetachDiskRequest.DetachDiskRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])
            req.set_DiskId(kwargs["DiskId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DetachDisk with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ReInitDisk(self, **kwargs):
        res = None
        try:
            req = ReInitDiskRequest.ReInitDiskRequest()
            req.set_accept_format("json")

            req.set_DiskId(kwargs["DiskId"])

            if "Password" in kwargs:
                req.set_Password(kwargs["Password"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ReInitDisk with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ResetDisk(self, **kwargs):
        res = None
        try:
            req = ResetDiskRequest.ResetDiskRequest()
            req.set_accept_format("json")

            req.set_DiskId(kwargs["DiskId"])
            req.set_SnapshotId(kwargs["SnapshotId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ReInitDisk with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ReplaceSystemDisk(self, **kwargs):
        res = None
        try:
            req = ReplaceSystemDiskRequest.ReplaceSystemDiskRequest()
            req.set_accept_format("json")

            req.set_InstanceId(kwargs["InstanceId"])
            req.set_ImageId(kwargs["ImageId"])

            if "SystemDiskSize" in kwargs:
                req.set_SystemDiskSize(kwargs["SystemDiskSize"])

            if "UseAdditionalService" in kwargs:
                # bool
                req.set_UseAdditionalService(kwargs["UseAdditionalService"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute ReplaceSystemDisk with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True

                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute ReplaceSystemDisk ...")
                    res = self.ReplaceSystemDisk(**kwargs)
                    if res["StatusCode"] == "200":
                        break
                    time.sleep(5)

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ReplaceSystemDisk with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ResizeDisk(self, **kwargs):
        res = None
        try:
            req = ResizeDiskRequest.ResizeDiskRequest()
            req.set_accept_format("json")

            req.set_DiskId(kwargs["DiskId"])
            req.set_NewSize(kwargs["NewSize"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to excute ResizeDisk with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

class ALiYunImageOperation(Singleton):

    def __init__(self, ak, secret, region_id):
        self.ak = ak
        self.secret = secret
        self.region_id = region_id
        self.clt = client.AcsClient(ak, secret, region_id)

    def CreateImage(self, **kwargs):
        res = None
        try:
            req = CreateImageRequest.CreateImageRequest()
            req.set_accept_format("json")

            if "SnapshotId" in kwargs:
                req.set_SnapshotId(kwargs["SnapshotId"])

            if "InstanceId" in kwargs:
                req.set_InstanceId(kwargs["InstanceId"])

            if "ImageName" in kwargs:
                req.set_ImageName(kwargs["ImageName"])

            if "ImageVersion" in kwargs:
                req.set_ImageVersion(kwargs["ImageVersion"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            for k, v in kwargs.items():
                if "DiskDeviceMapping" in k:
                    req.add_query_param(k, v)

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateImage with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True

                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute CreateImage ...")
                    res = self.CreateImage(**kwargs)
                    if res["StatusCode"] == "200":
                        break
                    time.sleep(5)

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateImage with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteImage(self, **kwargs):
        res = None
        try:
            req = DeleteImageRequest.DeleteImageRequest()
            req.set_accept_format("json")

            req.set_ImageId(kwargs["ImageId"])

            # if "Force" in kwargs:
            #     # bool
            #     req.set_Force(kwargs["Force"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteImage with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeImages(self, **kwargs):
        res = None
        try:
            req = DescribeImagesRequest.DescribeImagesRequest()
            req.set_accept_format("json")

            if "Status" in kwargs:
                req.set_Status(kwargs["Status"])

            if "ImageId" in kwargs:
                req.set_ImageId(kwargs["ImageId"])

            if "ShowExpired" in kwargs:
                # bool
                req.set_ShowExpired(kwargs["ShowExpired"])

            if "SnapshotId" in kwargs:
                req.set_SnapshotId(kwargs["SnapshotId"])

            if "ImageName" in kwargs:
                req.set_ImageName(kwargs["ImageName"])

            if "ImageOwnerAlias" in kwargs:
                req.set_ImageOwnerAlias(kwargs["ImageOwnerAlias"])

            if "InstanceType" in kwargs:
                req.set_InstanceType(kwargs["InstanceType"])

            if "IsSupportIoOptimized" in kwargs:
                req.set_IsSupportIoOptimized(kwargs["IsSupportIoOptimized"])

            # if "IsSupportCloudinit" in kwargs:
            #     req.set_IsSupportCloudinit(kwargs["IsSupportCloudinit"])

            if "OSType" in kwargs:
                req.set_OSType(kwargs["OSType"])

            if "Architecture" in kwargs:
                req.set_Architecture(kwargs["Architecture"])

            if "PageNumber" in kwargs:
                # int
                req.set_PageNumber(kwargs["PageNumber"])

            if "PageSize" in kwargs:
                # int
                req.set_PageSize(kwargs["PageSize"])

            if "Usage" in kwargs:
                req.set_Usage(kwargs["Usage"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeImages with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeImageSharePermission(self, **kwargs):
        res = None
        try:
            req = DescribeImageSharePermissionRequest.DescribeImageSharePermissionRequest()
            req.set_accept_format("json")

            req.set_ImageId(kwargs["ImageId"])

            if "PageNumber" in kwargs:
                # int
                req.set_PageNumber(kwargs["PageNumber"])

            if "PageSize" in kwargs:
                # int
                req.set_PageSize(kwargs["PageSize"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeImageSharePermission with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyImageAttribute(self, **kwargs):
        res = None
        try:
            req = ModifyImageAttributeRequest.ModifyImageAttributeRequest()
            req.set_accept_format("json")

            req.set_ImageId(kwargs["ImageId"])

            if "ImageName" in kwargs:
                req.set_ImageName(kwargs["ImageName"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyImageAttribute with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyImageSharePermission(self, **kwargs):
        res = None
        try:
            req = ModifyImageSharePermissionRequest.ModifyImageSharePermissionRequest()
            req.set_accept_format("json")

            req.set_ImageId(kwargs["ImageId"])

            for k, v in kwargs.items():
                if "AddAccount" in k:
                    nk = k.replace("AddAccount", "AddAccount.")
                    req.add_query_param(nk, v)
                if "RemoveAccount" in k:
                    nk = k.replace("RemoveAccount", "RemoveAccount.")
                    req.add_query_param(nk, v)

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyImageSharePermission with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    # The following are operations
    # CopyImage CancelCopyImage ImportImage
    def CopyImage(self, **kwargs):
        res = None
        try:
            req = CopyImageRequest.CopyImageRequest()
            req.set_accept_format("json")

            req.set_ImageId(kwargs["ImageId"])
            req.set_DestinationRegionId(kwargs["DestinationRegionId"])

            if "DestinationImageName" in kwargs:
                req.set_DestinationImageName(kwargs["DestinationImageName"])

            if "DestinationDescription" in kwargs:
                req.set_DestinationDescription(kwargs["DestinationDescription"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CopyImage with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CancelCopyImage(self, **kwargs):
        res = None
        try:
            req = CancelCopyImageRequest.CancelCopyImageRequest()
            req.set_accept_format("json")

            req.set_ImageId(kwargs["ImageId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CancelCopyImage with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ImportImage(self, **kwargs):
        res = None
        try:
            req = ImportImageRequest.ImportImageRequest()
            req.set_accept_format("json")

            if "ImageName" in kwargs:
                req.set_ImageName(kwargs["ImageName"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            if "Architecture" in kwargs:
                req.set_Architecture(kwargs["Architecture"])

            if "OSType" in kwargs:
                req.set_OSType(kwargs["OSType"])

            if "Platform" in kwargs:
                req.set_Platform(kwargs["Platform"])
            p = re.compile("(\d+)")
            for k, v in kwargs.items():
                if "DiskDeviceMapping" in k:
                    # DiskImSize DiskImageSize is int
                    nk = '.'.join(p.split(k))
                    req.add_query_param(nk, v)

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception  as ex:
            debug(traceback.format_exc())
            error("Failed to execute ImportImage with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

class ALiYunSnapshotOperation(Singleton):

    def __init__(self, ak, secret, region_id):
        self.ak = ak
        self.secret = secret
        self.region_id = region_id
        self.clt = client.AcsClient(ak, secret, region_id)

    def CreateSnapshot(self, **kwargs):
        res = None
        try:
            req = CreateSnapshotRequest.CreateSnapshotRequest()
            req.set_accept_format("json")

            req.set_DiskId(kwargs["DiskId"])

            if "SnapshotName" in kwargs:
                req.set_SnapshotName(kwargs["SnapshotName"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            if "ClientToken" in kwargs:
                req.set_ClientToken(kwargs["ClientToken"])
            else:
                kwargs["ClientToken"] = "%d" % (time.time())
                req.set_ClientToken(kwargs["ClientToken"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateSnapshot with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True

                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute CreateSnapshot ...")
                    res = self.CreateSnapshot(**kwargs)
                    if res["StatusCode"] == "200":
                        break

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateSnapshot with some exceptions %s." % (ex))
            res = {"StatusCode" : "403", "Message" : str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CreateAutoSnapshotPolicy(self, **kwargs):
        res = None
        try:
            req = CreateAutoSnapshotPolicyRequest.CreateAutoSnapshotPolicyRequest()
            req.set_accept_format("json")

            req.set_timePoints(kwargs["TimePoints"])
            req.set_repeatWeekdays(kwargs["RepeatWeekdays"])
            # int
            req.set_retentionDays(kwargs["RetentionDays"])
            req.set_autoSnapshotPolicyName(kwargs["AutoSnapshotPolicyName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateAutoSnapshotPolicy with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteSnapshot(self, **kwargs):
        res = None
        try:
            req = DeleteSnapshotRequest.DeleteSnapshotRequest()
            req.set_accept_format("json")

            req.set_SnapshotId(kwargs["SnapshotId"])

            # if "Force" in kwargs:
            #     req.set_Force (kwargs["Force"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteSnapshot with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteAutoSnapshotPolicy(self, **kwargs):
        res = None
        try:
            req = DeleteAutoSnapshotPolicyRequest.DeleteAutoSnapshotPolicyRequest()
            req.set_accept_format("json")

            req.set_autoSnapshotPolicyId(kwargs["AutoSnapshotPolicyId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteAutoSnapshotPolicy with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeSnapshots(self, **kwargs):
        res = None
        try:
            req = DescribeSnapshotsRequest.DescribeSnapshotsRequest()
            req.set_accept_format("json")

            if "InstanceId" in kwargs:
                req.set_InstanceId(kwargs["InstanceId"])

            if "DiskId" in kwargs:
                req.set_DiskId(kwargs["DiskId"])

            if "SnapshotLinkId" in kwargs:
                req.set_SnapshotLinkId(kwargs["SnapshotLinkId"])

            if "SnapshotIds" in kwargs:
                req.set_SnapshotIds(kwargs["SnapshotIds"])

            if "SnapshotName" in kwargs:
                req.set_SnapshotName(kwargs["SnapshotName"])

            if "Status" in kwargs:
                req.set_Status(kwargs["Status"])

            if "SnapshotType" in kwargs:
                req.set_SnapshotType(kwargs["SnapshotType"])

            if "SourceDiskType" in kwargs:
                req.set_SourceDiskType(kwargs["SourceDiskType"])

            if "Usage" in kwargs:
                req.set_Usage(kwargs["Usage"])

            if "PageNumber" in kwargs:
                # int
                req.set_PageNumber(kwargs["PageNumber"])

            if "PageSize" in kwargs:
                # int
                req.set_PageSize(kwargs["PageSize"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeSnapshots with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    # In aliyun sdk this method maybe abolished
    def DescribeAutoSnapshotPolicy(self, **kwargs):
        res = None
        try:
            req = DescribeAutoSnapshotPolicyRequest.DescribeAutoSnapshotPolicyRequest()
            req.set_accept_format("json")

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeAutoSnapshotPolicy with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeAutoSnapshotPolicyEx(self, **kwargs):
        res = None
        try:
            req = DescribeAutoSnapshotPolicyExRequest.DescribeAutoSnapshotPolicyExRequest()
            req.set_accept_format("json")

            req.set_AutoSnapshotPolicyId(kwargs["AutoSnapshotPolicyId"])

            if "PageNumber" in kwargs:
                # int
                req.set_PageNumber(kwargs["PageNumber"])

            if "PageSize" in kwargs:
                # int
                req.set_PageSize(kwargs["PageSize"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeAutoSnapshotPolicyEx with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifySnapshotAttribute(self, **kwargs):
        res = None
        try:
            req = ModifySnapshotAttributeRequest.ModifySnapshotAttributeRequest()
            req.set_accept_format("json")

            req.set_SnapshotId(kwargs["SnapshotId"])

            if "Description" in kwargs:
                req.set_Description(kwargs["Description"])

            if "SnapshotName" in kwargs:
                req.set_SnapshotName(kwargs["SnapshotName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifySnapshotAttribute with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyAutoSnapshotPolicyEx(self, **kwargs):
        res = None
        try:
            req = ModifyAutoSnapshotPolicyExRequest.ModifyAutoSnapshotPolicyExRequest()
            req.set_accept_format("json")

            req.set_autoSnapshotPolicyId(kwargs["AutoSnapshotPolicyId"])

            if "AutoSnapshotPolicyName" in kwargs:
                req.set_autoSnapshotPolicyName(kwargs["AutoSnapshotPolicyName"])

            if "TimePoints" in kwargs:
                req.set_timePoints(kwargs["TimePoints"])

            if "RepeatWeekdays" in kwargs:
                req.set_repeatWeekdays(kwargs["RepeatWeekdays"])

            if "RetentionDays" in kwargs:
                # int
                req.set_retentionDays(kwargs["RetentionDays"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyAutoSnapshotPolicyEx with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    # The following are operations
    def ApplyAutoSnapshotPolicy(self, **kwargs):
        res = None
        try:
            req = ApplyAutoSnapshotPolicyRequest.ApplyAutoSnapshotPolicyRequest()
            req.set_accept_format("json")

            req.set_autoSnapshotPolicyId(kwargs["AutoSnapshotPolicyId"])
            req.set_diskIds(kwargs["DiskIds"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ApplyAutoSnapshotPolicy with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CancelAutoSnapshotPolicy(self, **kwargs):
        res = None
        try:
            req = CancelAutoSnapshotPolicyRequest.CancelAutoSnapshotPolicyRequest()
            req.set_accept_format("json")
            req.set_diskIds(kwargs["DiskIds"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CancelAutoSnapshotPolicy with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

class ALiyunSSHKeypairOperation(Singleton):

    def __init__(self, ak, secret, region_id):
        self.ak = ak
        self.secret = secret
        self.region_id = region_id
        self.clt = client.AcsClient(ak, secret, region_id)

    def CreateKeyPair(self, **kwargs):
        res = None
        try:
            req = CreateKeyPairRequest.CreateKeyPairRequest()
            req.set_accept_format("json")

            req.set_KeyPairName(kwargs["KeyPairName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateKeyPair with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteKeyPairs(self, **kwargs):
        res = None
        try:
            req = DeleteKeyPairsRequest.DeleteKeyPairsRequest()
            req.set_accept_format("json")

            req.set_KeyPairNames(kwargs["KeyPairNames"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeKeyPairs with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeKeyPairs(self, **kwargs):
        res = None
        try:
            req = DescribeKeyPairsRequest.DescribeKeyPairsRequest()
            req.set_accept_format("json")

            if "KeyPairName" in kwargs:
                req.set_KeyPairName(kwargs["KeyPairName"])

            if "KeyPairFingerPrint" in kwargs:
                req.set_KeyPairFingerPrint(kwargs["KeyPairFingerPrint"])

            if "PageNumber" in kwargs:
                # int
                req.set_PageNumber(kwargs["PageNumber"])

            if "PageSize" in kwargs:
                # int
                req.set_PageSize(kwargs["PageSize"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeKeyPairs with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    # The following are operations
    def ImportKeyPair(self, **kwargs):
        res = None
        try:
            req = ImportKeyPairRequest.ImportKeyPairRequest()
            req.set_accept_format("json")

            req.set_PublicKeyBody(kwargs["PublicKeyBody"])
            req.set_KeyPairName(kwargs["KeyPairName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ImportKeyPair with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def AttachKeyPair(self, **kwargs):
        res = None
        try:
            req = AttachKeyPairRequest.AttachKeyPairRequest()
            req.set_accept_format("json")

            req.set_KeyPairName(kwargs["KeyPairName"])
            req.set_InstanceIds(kwargs["InstanceIds"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute AttachKeyPair with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DetachKeyPair(self, **kwargs):
        res = None
        try:
            req = DetachKeyPairRequest.DetachKeyPairRequest()
            req.set_accept_format("json")

            req.set_KeyPairName(kwargs["KeyPairName"])
            req.set_InstanceIds(kwargs["InstanceIds"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DetachKeyPair with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

class ALiYunRdsOperation(Singleton):

    def __init__(self, ak, secret, region_id):
        self.ak = ak
        self.secret = secret
        self.region_id = region_id
        self.clt = client.AcsClient(ak, secret, region_id, timeout=3000)

    def CreateDBInstance(self, **kwargs):
        res = None
        try:
            req = CreateDBInstanceRequest.CreateDBInstanceRequest()
            req.set_accept_format("json")

            req.set_Engine(kwargs["Engine"])
            req.set_EngineVersion(kwargs["EngineVersion"])
            req.set_DBInstanceClass(kwargs["DBInstanceClass"])
            # int
            req.set_DBInstanceStorage(kwargs["DBInstanceStorage"])
            req.set_DBInstanceNetType(kwargs["DBInstanceNetType"])
            req.set_SecurityIPList(kwargs["SecurityIPList"])
            req.set_PayType(kwargs["PayType"])

            if "ZoneId" in kwargs:
                req.set_ZoneId(kwargs["ZoneId"])
            if "DBInstanceDescription" in kwargs:
                req.set_DBInstanceDescription(kwargs["DBInstanceDescription"])
            if "Period" in kwargs:
                req.set_Period(kwargs["Period"])
            if "UsedTime" in kwargs:
                req.set_UsedTime(kwargs["UserTime"])
            if "ClientToken" in kwargs:
                req.set_ClientToken(kwargs["ClientToken"])
            else:
                # set the client token by self
                kwargs["ClientToken"] = str(time.time())
                req.set_ClientToken(kwargs["ClientToken"])
            if "InstanceNetworkType" in kwargs:
                req.set_InstanceNetworkType(kwargs["InstanceNetworkType"])
            if "ConnectionMode" in kwargs:
                req.set_ConnectionMode(kwargs["ConnectionMode"])
            if "VpcId" in kwargs:
                req.set_VPCId(kwargs["VpcId"])
            if "VSwitchId" in kwargs:
                req.set_VSwitchId(kwargs["VSwitchId"])
            if "PrivateIpAddress" in kwargs:
                req.set_PrivateIpAddress(kwargs["PrivateIpAddress"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateDBInstance with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                for i in range(1,3):
                    # try max 3 times to create the db instance
                    info("Try again to execute CreateDBInstance ...")
                    res = self.CreateDBInstance(**kwargs)
                    if res["StatusCode"] == "200":
                        break
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateDBInstance with some exceptions %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteDBInstance(self, **kwargs):
        res = None
        try:
            req = DeleteDBInstanceRequest.DeleteDBInstanceRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            debug("Failed to execute DeleteDBInstance with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                for i in range(1, 3):
                    # try max 3 times to delete db instance
                    time.sleep(3)
                    info("Try again to execute DeleteDBInstance ...")
                    res = self.DeleteDBInstance(**kwargs)
                    if res["StatusCode"] == "200":
                        break

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteDBInstance with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def RestartDBInstance(self, **kwargs):
        res = None
        try:
            req = RestartDBInstanceRequest.RestartDBInstanceRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute RestartDBInstance with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDBInstanceAttribute(self, **kwargs):
        res = None
        try:
            req = DescribeDBInstanceAttributeRequest.DescribeDBInstanceAttributeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDBInstanceAttribute with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDBInstances(self, **kwargs):
        res = None
        try:
            req = DescribeDBInstancesRequest.DescribeDBInstancesRequest()
            req.set_accept_format("json")

            if "Engine" in kwargs:
                req.set_Engine(kwargs["Engine"])
            if "DBInstanceType" in kwargs:
                req.set_DBInstanceType(kwargs["DBInstanceType"])
            if "InstanceNetworkType" in kwargs:
                req.set_InstanceNetworkType(kwargs["InstanceNetworkType"])
            if "ConnectionMode" in kwargs:
                req.set_ConnectionMode(kwargs["ConnectionMode"])
            if "Tags" in kwargs:
                req.set_Tags(kwargs["Tags"])
            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDBInstances with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceSpec(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceSpecRequest.ModifyDBInstanceSpecRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_PayType(kwargs["PayType"])

            if "DBInstanceClass" in kwargs:
                req.set_DBInstanceClass(kwargs["DBInstanceClass"])
            if "DBInstanceStorage" in kwargs:
                req.set_DBInstanceStorage(kwargs["DBInstanceStorage"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceSpec with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstancePayType(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstancePayTypeRequest.ModifyDBInstancePayTypeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_PayType(kwargs["PayType"])

            if "Period" in kwargs:
                req.set_Period(kwargs["Period"])
            if "UsedTime" in kwargs:
                req.set_UsedTime(kwargs["UsedTime"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstancePayType with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyInstanceAutoRenewalAttribute(self, **kwargs):
        res = None
        try:
            req = ModifyInstanceAutoRenewalAttributeRequest.ModifyInstanceAutoRenewalAttributeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_AutoRenew(kwargs["AutoRenew"])

            if "Duration" in kwargs:
                req.set_Duration(kwargs["Duration"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyInstanceAutoRenewalAttribute with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def AllocateInstancePublicConnection(self, **kwargs):
        res = None
        try:
            req = AllocateInstancePublicConnectionRequest.AllocateInstancePublicConnectionRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_ConnectionStringPrefix(kwargs["ConnectionStringPrefix"])
            req.set_Port(kwargs["Port"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute AllocateInstancePulicConnection with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ReleaseInstancePublicConnection(self, **kwargs):
        res = None
        try:
            req = ReleaseInstancePublicConnectionRequest.ReleaseInstancePublicConnectionRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_CurrentConnectionString(kwargs["CurrentConnectionString"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ReleaseInstancePublicConnection with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def SwitchDBInstanceNetType(self, **kwargs):
        res = None
        try:
            req = SwitchDBInstanceNetTypeRequest.SwitchDBInstanceNetTypeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_ConnectionStringPrefix(kwargs["ConnectionStringPrefix"])

            if "Port" in kwargs:
                req.set_Port(kwargs["Port"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute SwitchDBInstanceNetType with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDBInstanceNetInfo(self, **kwargs):
        res = None
        try:
            req = DescribeDBInstanceNetInfoRequest.DescribeDBInstanceNetInfoRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            # if "ConnectionStringType" in kwargs:
            #     req.set_ConnectionStringType(kwargs["ConnectionStringType"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDBInstanceNetInfo with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceConnectionString(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceConnectionStringRequest.ModifyDBInstanceConnectionStringRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_CurrentConnectionString(kwargs["CurrentConnectionString"])

            if "ConnectionStringPrefix" in kwargs:
                req.set_ConnectionStringPrefix(kwargs["ConnectionStringPrefix"])
            if "Port" in kwargs:
                # int
                req.set_Port(kwargs["Port"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceConnectionString with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute ModifyDBInstanceConnectionString ...")
                    res = self.ModifyDBInstanceConnectionString(**kwargs)
                    if res["StatusCode"] == "200":
                        break
                    time.sleep(5)

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceConnectionString with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceConnectionMode(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceConnectionModeRequest.ModifyDBInstanceConnectionModeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_ConnectionMode(kwargs["ConnectionMode"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceConnectionMode with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceNetworkType(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceNetworkTypeRequest.ModifyDBInstanceNetworkTypeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_InstanceNetworkType(kwargs["InstanceNetworkType"])

            if "VPCId" in kwargs:
                req.set_VPCId(kwargs["VPCId"])
            if "VSwitchId" in kwargs:
                req.set_VSwitchId(kwargs["VSwitchId"])
            if "PrivateIpAddress" in kwargs:
                req.set_PrivateIpAddress(kwargs["PrivateIpAddress"])
            if "ReadWriteSplittingPrivateIpAddress" in kwargs:
                req.set_ReadWriteSplittingPrivateIpAddress(kwargs["ReadWriteSplittingPrivateIpAddress"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceConnectionMode with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDBInstanceIPArrayList(self, **kwargs):
        res = None
        try:
            req = DescribeDBInstanceIPArrayListRequest.DescribeDBInstanceIPArrayListRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDBInstanceIPArrayList with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifySecurityIps(self, **kwargs):
        res = None
        try:
            req = ModifySecurityIpsRequest.ModifySecurityIpsRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            if "SecurityIps" in kwargs:
                req.set_SecurityIps(kwargs["SecurityIps"])
            if "DBInstanceIPArrayName" in kwargs:
                req.set_DBInstanceIPArrayName(kwargs["DBInstanceIPArrayName"])
            if "DBInstanceIPArrayAttribute" in kwargs:
                req.set_DBInstanceIPArrayAttribute(kwargs["DBInstanceIPArrayAttribute"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifySecurityIps with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeRegions(self, **kwargs):
        res = None
        try:
            req = DescribeRegionsRequest.DescribeRegionsRequest()
            req.set_accept_format("json")

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifySecurityIps with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDBInstanceHAConfig(self, **kwargs):
        res = None
        try:
            req = DescribeDBInstanceHAConfigRequest.DescribeDBInstanceHAConfigRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDBInstanceHAConfigRequest with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def MigrateToOtherZone(self, **kwargs):
        res = None
        try:
            req = MigrateToOtherZoneRequest.MigrateToOtherZoneRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_ZoneId(kwargs["ZoneId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute MigrateToOtherZoneRequest with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def PurgeDBInstanceLog(self, **kwargs):
        res = None
        try:
            req = PurgeDBInstanceLogRequest.PurgeDBInstanceLogRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute PurgeDBInstanceLog with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res
    
    def UpgradeDBInstanceEngineVersion(self, **kwargs):
        res = None
        try:
            req = UpgradeDBInstanceEngineVersionRequest.UpgradeDBInstanceEngineVersionRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_EngineVersion(kwargs["EngineVersion"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute UpgradeDBInstanceEngineVersion with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceDescription(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceDescriptionRequest.ModifyDBInstanceDescriptionRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_DBInstanceDescription(kwargs["DBInstanceDescription"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceDescription with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceMaintainTime(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceMaintainTimeRequest.ModifyDBInstanceMaintainTimeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_MaintainTime(kwargs["MaintainTime"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceMaintainTime with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceHAConfig(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceHAConfigRequest.ModifyDBInstanceHAConfigRequest()
            req.set_accept_format("json")

            req.set_DbInstanceId(kwargs["DBInstanceId"])
            req.set_SyncMode(kwargs["SyncMode"])
            req.set_HAMode(kwargs["HAMode"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceHAConfig with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def SwitchDBInstanceHA(self, **kwargs):
        res = None
        try:
            req = SwitchDBInstanceHARequest.SwitchDBInstanceHARequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_NodeId(kwargs["NodeId"])
            req.set_Force(kwargs["Force"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute SwitchDBInstanceHA with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CreateReadOnlyDBInstance(self, **kwargs):
        res = None
        try:
            req = CreateReadOnlyDBInstanceRequest.CreateReadOnlyDBInstanceRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_ZoneId(kwargs["ZoneId"])
            req.set_EngineVersion(kwargs["EngineVersion"])
            req.set_DBInstanceClass(kwargs["DBInstanceClass"])
            req.set_DBInstanceStorage(kwargs["DBInstanceStorage"])
            req.set_PayType(kwargs["PayType"])

            if "ClientToken" in kwargs:
                req.set_ClientToken(kwargs["ClientToken"])
            else:
                req.set_ClientToken(str(time.time()))
            if "DBInstanceDescription" in kwargs:
                req.set_DBInstanceDescription(kwargs["DBInstanceDescription"])
            if "InstanceNetworkType" in kwargs:
                req.set_InstanceNetworkType(kwargs["InstanceNetworkType"])
            if "VPCId" in kwargs:
                req.set_VPCId(kwargs["VPCId"])
            if "VSwitchId" in kwargs:
                req.set_VSwitchId(kwargs["VSwitchId"])
            if "PrivateIpAddress" in kwargs:
                req.set_PrivateIpAddress(kwargs["PrivateIpAddress"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateReadOnlyDBInstance with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDBInstanceSSL(self, **kwargs):
        res = None
        try:
            req = DescribeDBInstanceSSLRequest.DescribeDBInstanceSSLRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDBInstanceSSL with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceSSL(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceSSLRequest.ModifyDBInstanceSSLRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_ConnectionString(kwargs["ConnectionString"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceSSL with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDBInstanceTDE(self, **kwargs):
        res = None
        try:
            req = DescribeDBInstanceTDERequest.DescribeDBInstanceTDERequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDBInstanceTDE with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceTDE(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceTDERequest.ModifyDBInstanceTDERequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_TDEStatus(kwargs["TDEStatus"])

            if "DBName" in kwargs:
                req.set_DBName(kwargs["DBName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceTDE with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceNetworkExpireTime(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceNetworkExpireTimeRequest.ModifyDBInstanceNetworkExpireTimeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_ConnectionString(kwargs["ConnectionString"])
            # int
            req.set_ClassicExpiredDays(kwargs["ClassicExpiredDays"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceNetworkExpireTime with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CreateDatabase(self, **kwargs):
        res = None
        try:
            req = CreateDatabaseRequest.CreateDatabaseRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_DBName(kwargs["DBName"])
            req.set_CharacterSetName(kwargs["CharacterSetName"])

            if "DBDescription" in kwargs:
                req.set_DBDescription(kwargs["DBDescription"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateDatabase with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteDatabase(self, **kwargs):
        res = None
        try:
            req = DeleteDatabaseRequest.DeleteDatabaseRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_DBName(kwargs["DBName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteDatabase with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDatabases(self, **kwargs):
        res = None
        try:
            req = DescribeDatabasesRequest.DescribeDatabasesRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_DBName(kwargs["DBName"])

            if "DBStatus" in kwargs:
                req.set_DBStatus(kwargs["DBStatus"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDatabases with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBDescription(self, **kwargs):
        res = None
        try:
            req = ModifyDBDescriptionRequest.ModifyDBDescriptionRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_DBName(kwargs["DBName"])
            req.set_DBDescription(kwargs["DBDescription"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBDescription with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CreateBackup(self, **kwargs):
        res = None
        try:
            req = CreateBackupRequest.CreateBackupRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            if "BackupMethod" in kwargs:
                req.set_BackupMethod(kwargs["BackupMethod"])
            # if "BackupStrategy" in kwargs:
            #     req.set_BackupStrategy(kwargs["BackupStrategy"])
            if "DBName" in kwargs:
                req.set_DBName(kwargs["DBName"])
            if "BackupType" in kwargs:
                req.set_BackupType(kwargs["BackupType"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateBackup with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CloneDBInstance(self, **kwargs):
        res = None
        try:
            req = CloneDBInstanceRequest.CloneDBInstanceRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_PayType(kwargs["PayType"])

            if "BackupId" in kwargs:
                req.set_BackupId(kwargs["BackupId"])
            if "RestoreTime" in kwargs:
                req.set_RestoreTime(kwargs["RestoreTime"])
            if "Period" in kwargs:
                req.set_Period(kwargs["Period"])
            if "UsedTime" in kwargs:
                req.set_UsedTime(kwargs["UsedTime"])
            if "DBInstanceClass" in kwargs:
                req.set_DBInstanceClass(kwargs["DBInstanceClass"])
            if "DBInstanceStorage" in kwargs:
                req.set_DBInstanceStorage(kwargs["DBInstanceStorage"])
            if "InstanceNetworkType" in kwargs:
                req.set_InstanceNetworkType(kwargs["InstanceNetworkType"])
            if "VPCId" in kwargs:
                req.set_VPCId(kwargs["VPCId"])
            if "VSwitichId" in kwargs:
                req.set_VSwitchId(kwargs["VSwitichId"])
            if "PrivateIpAddress" in kwargs:
                req.set_PrivateIpAddress(kwargs["PrivateIpAddress"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CloneDBInstance with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeBackups(self, **kwargs):
        res = None
        try:
            req = DescribeBackupsRequest.DescribeBackupsRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            if "BackupId" in kwargs:
                req.set_BackupId(kwargs["BackupId"])
            if "BackupStatus" in kwargs:
                req.set_BackupStatus(kwargs["BackupStatus"])
            if "BackupMode" in kwargs:
                req.set_BackupMode(kwargs["BackupMode"])
            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeBackups with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CreateTempDBInstance(self, **kwargs):
        res = None
        try:
            req = CreateTempDBInstanceRequest.CreateTempDBInstanceRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            if "BackupId" in kwargs:
                req.set_BackupId(kwargs["BackupId"])
            if "RestoreTime" in kwargs:
                req.set_RestoreTime(kwargs["RestoreTime"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateTempDBInstance with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeBackupPolicy(self, **kwargs):
        res = None
        try:
            req = DescribeBackupPolicyRequest.DescribeBackupPolicyRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeBackupPolicy with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyBackupPolicy(self, **kwargs):
        res = None
        try:
            req = ModifyBackupPolicyRequest.ModifyBackupPolicyRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_PreferredBackupTime(kwargs["PreferredBackupTime"])
            req.set_PreferredBackupPeriod(kwargs["PreferredBackupPeriod"])
            
            if "BackupRetentionPeriod" in kwargs:
                req.set_BackupRetentionPeriod(kwargs["BackupRetentionPeriod"])
            if "BackupLog" in kwargs:
                req.set_BackupLog(kwargs["BackupLog"])
            if "LogBackupRetentionPeriod" in kwargs:
                req.set_LogBackupRetentionPeriod(kwargs["LogBackupRetentionPeriod"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyBackupPolicy with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def RestoreDBInstance(self, **kwargs):
        res = None
        try:
            req = RestoreDBInstanceRequest.RestoreDBInstanceRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_BackupId(kwargs["BackupId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute RestoreDBInstance with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteBackup(self, **kwargs):
        res = None
        try:
            req = DeleteBackupRequest.DeleteBackupRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_BackupId(kwargs["BackupId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteBackup with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def AllocateReadWriteSplittingConnection(self, **kwargs):
        res = None
        try:
            req = AllocateReadWriteSplittingConnectionRequest.AllocateReadWriteSplittingConnectionRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_DistributionType(kwargs["DistributionType"])

            if "ConnectionStringPrefix" in kwargs:
                req.set_ConnectionStringPrefix(kwargs["ConnectionStringPrefix"])
            if "Port" in kwargs:
                req.set_Port(kwargs["Port"])
            if "MaxDelayTime" in kwargs:
                req.set_MaxDelayTime(kwargs["MaxDelayTime"])
            # if "NetType" in kwargs:
            #     req.set_NetType(kwargs["NetType"])
            # if "PrivateIpAddress" in kwargs:
            #     req.set_PrivateIpAddress(kwargs["PrivateIpAddress"])
            if "Weight" in kwargs:
                req.set_Weight(kwargs["Weight"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute AllocateReadWriteSplittingConnection with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CalculateDBInstanceWeight(self, **kwargs):
        res = None
        try:
            req = CalculateDBInstanceWeightRequest.CalculateDBInstanceWeightRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CalculateDBInstanceWeight with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyReadWriteSplittingConnection(self, **kwargs):
        res = None
        try:
            req = ModifyReadWriteSplittingConnectionRequest.ModifyReadWriteSplittingConnectionRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            if "MaxDelayTime" in kwargs:
                req.set_MaxDelayTime(kwargs["MaxDelayTime"])
            if "DistributionType" in kwargs:
                req.set_DistributionType(kwargs["DistributionType"])
            if "Weight" in kwargs:
                req.set_Weight(kwargs["Weight"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyReadWriteSplittingConnection with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ReleaseReadWriteSplittingConnection(self, **kwargs):
        res = None
        try:
            req = ReleaseReadWriteSplittingConnectionRequest.ReleaseReadWriteSplittingConnectionRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ReleaseReadWriteSplittingConnection with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CreateAccount(self, **kwargs):
        res = None
        try:
            req = CreateAccountRequest.CreateAccountRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_AccountName(kwargs["AccountName"])
            req.set_AccountPassword(kwargs["AccountPassword"])

            if "AccountType" in kwargs:
                req.set_AccountType(kwargs["AccountType"])
            if "AccountDescription" in kwargs:
                req.set_AccountDescription(kwargs["AccountDescription"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""

        except ServerException as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateAccount with some exceptions %s." % (ex))
            if "Recursion" in kwargs and kwargs["Recursion"]:
                res = {"StatusCode": "403", "Message": str(ex)}
                res["RequestId"] = _get_exception_response_id(res["Message"])
            else:
                kwargs["Recursion"] = True
                for i in range(1, 3):
                    # try max 3 times to create the db instance
                    info("Try again to execute CreateAccount ...")
                    res = self.CreateAccount(**kwargs)
                    if res["StatusCode"] == "200":
                        break
                    time.sleep(5)

        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateAccount with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DeleteAccount(self, **kwargs):
        res = None
        try:
            req = DeleteAccountRequest.DeleteAccountRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_AccountName(kwargs["AccountName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DeleteAccount with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeAccounts(self, **kwargs):
        res = None
        try:
            req = DescribeAccountsRequest.DescribeAccountsRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_AccountName(kwargs["AccountName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeAccounts with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def GrantAccountPrivilege(self, **kwargs):
        res = None
        try:
            req = GrantAccountPrivilegeRequest.GrantAccountPrivilegeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_AccountName(kwargs["AccountName"])
            req.set_DBName(kwargs["DBName"])

            if "AccountPrivilege" in kwargs:
                req.set_AccountPrivilege(kwargs["AccountPrivilege"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute GrantAccountPrivilege with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def RevokeAccountPrivilege(self, **kwargs):
        res = None
        try:
            req = RevokeAccountPrivilegeRequest.RevokeAccountPrivilegeRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_AccountName(kwargs["AccountName"])
            req.set_DBName(kwargs["DBName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute RevokeAccountPrivilege with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyAccountDescription(self, **kwargs):
        res = None
        try:
            req = ModifyAccountDescriptionRequest.ModifyAccountDescriptionRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_AccountName(kwargs["AccountName"])
            req.set_AccountDescription(kwargs["AccountDescription"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyAccountDescription with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ResetAccountPassword(self, **kwargs):
        res = None
        try:
            req = ResetAccountPasswordRequest.ResetAccountPasswordRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_AccountName(kwargs["AccountName"])
            req.set_AccountPassword(kwargs["AccountPassword"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ResetAccountPassword with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ResetAccount(self, **kwargs):
        res = None
        try:
            req = ResetAccountForPGRequest.ResetAccountForPGRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_AccountName(kwargs["AccountName"])
            req.set_AccountPassword(kwargs["AccountPassword"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ResetAccount with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeSlowLogs(self, **kwargs):
        res = None
        try:
            req = DescribeSlowLogsRequest.DescribeSlowLogsRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            if "DBName" in kwargs:
                req.set_DBName(kwargs["DBName"])
            if "SortKey" in kwargs:
                req.set_SortKey(kwargs["SortKey"])
            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeSlowLogs with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeSlowLogRecords(self, **kwargs):
        res = None
        try:
            req = DescribeSlowLogRecordsRequest.DescribeSlowLogRecordsRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            if "DBName" in kwargs:
                req.set_DBName(kwargs["DBName"])
            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeSlowLogRecords with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeErrorLogs(self, **kwargs):
        res = None
        try:
            req = DescribeErrorLogsRequest.DescribeErrorLogsRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeErrorLogs with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeBinlogFiles(self, **kwargs):
        res = None
        try:
            req = DescribeBinlogFilesRequest.DescribeBinlogFilesRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeBinlogFiles with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeSQLCollectorPolicy(self, **kwargs):
        res = None
        try:
            req = DescribeSQLCollectorPolicyRequest.DescribeSQLCollectorPolicyRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeSQLCollectorPolicy with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifySQLCollectorPolicy(self, **kwargs):
        res = None
        try:
            req = ModifySQLCollectorPolicyRequest.ModifySQLCollectorPolicyRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_SQLCollectorStatus(kwargs["SQLCollectorStatus"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifySQLCollectorPolicy with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeSQLLogRecords(self, **kwargs):
        res = None
        try:
            req = DescribeSQLLogRecordsRequest.DescribeSQLLogRecordsRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            if "Database" in kwargs:
                req.set_Database(kwargs["Database"])
            if "User" in kwargs:
                req.set_User(kwargs["User"])
            if "Form" in kwargs:
                req.set_Form(kwargs["Form"])
            if "QueryKeywords" in kwargs:
                req.set_QueryKeywords(kwargs["QueryKeywords"])
            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeSQLLogRecords with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeSQLLogFiles(self, **kwargs):
        res = None
        try:
            req = DescribeSQLLogFilesRequest.DescribeSQLLogFilesRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeSQLLogFiles with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeResourceUsage(self, **kwargs):
        res = None
        try:
            req = DescribeResourceUsageRequest.DescribeResourceUsageRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeResourceUsage with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDBInstancePerformance(self, **kwargs):
        res = None
        try:
            req = DescribeDBInstancePerformanceRequest.DescribeDBInstancePerformanceRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_Key(kwargs["Key"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDBInstancePerformance with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeDBInstanceMonitor(self, **kwargs):
        # 查询监控行为
        res = None
        try:
            req = DescribeDBInstanceMonitorRequest.DescribeDBInstanceMonitorRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeDBInstanceMonitor with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyDBInstanceMonitor(self, **kwargs):
        res = None
        try:
            req = ModifyDBInstanceMonitorRequest.ModifyDBInstanceMonitorRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_Period(kwargs["Period"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyDBInstanceMonitor with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeParameterTemplates(self, **kwargs):
        res = None
        try:
            req = DescribeParameterTemplatesRequest.DescribeParameterTemplatesRequest()
            req.set_accept_format("json")

            req.set_Engine(kwargs["Engine"])
            req.set_EngineVersion(kwargs["EngineVersion"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeParameterTemplates with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeParameters(self, **kwargs):
        res = None
        try:
            req = DescribeParametersRequest.DescribeParametersRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeParameters with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ModifyParameter(self, **kwargs):
        res = None
        try:
            req = ModifyParameterRequest.ModifyParameterRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_Parameters(kwargs["ModifyParameter"])

            if "Forcerestart" in kwargs:
                req.set_Forcerestart(kwargs["Forcerestart"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ModifyParameter with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CreateUploadPathForSQLServer(self, **kwargs):
        res = None
        try:
            req = CreateUploadPathForSQLServerRequest.CreateUploadPathForSQLServerRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_DBName(kwargs["DBName"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CreateUploadPathForSQLServer with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeFilesForSQLServer(self, **kwargs):
        res = None
        try:
            req = DescribeFilesForSQLServerRequest.DescribeFilesForSQLServerRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeFilesForSQLServer with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeImportsForSQLServer(self, **kwargs):
        res = None
        try:
            req = DescribeImportsForSQLServerRequest.DescribeImportsForSQLServerRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])
            if "ImportId" in kwargs:
                req.set_ImportId(kwargs["ImportId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeImportsForSQLServer with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def ImportDatabaseBetweenInstances(self, **kwargs):
        res = None
        try:
            req = ImportDatabaseBetweenInstancesRequest.ImportDatabaseBetweenInstancesRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_SourceDBInstanceId(kwargs["SourceDBInstanceId"])
            req.set_DBInfo(kwargs["DBInfo"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute ImportDatabaseBetweenInstances with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def CancelImport(self, **kwargs):
        res = None
        try:
            req = CancelImportRequest.CancelImportRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_ImportId(kwargs["ImportId"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute CancelImport with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeSQLLogReports(self, **kwargs):
        res = None
        try:
            req = DescribeSQLLogReportsRequest.DescribeSQLLogReportsRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_StartTime(kwargs["StartTime"])
            req.set_EndTime(kwargs["EndTime"])

            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeSQLLogReports with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeOptimizeAdviceOnMissIndex(self, **kwargs):
        res = None
        try:
            req = DescribeOptimizeAdviceOnMissIndexRequest.DescribeOptimizeAdviceOnMissIndexRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])

            if "PageSize" in kwargs:
                req.set_PageSize(kwargs["PageSize"])
            if "PageNumber" in kwargs:
                req.set_PageNumber(kwargs["PageNumber"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeOptimizeAdviceOnMissIndex with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def AddTagsToResource(self, **kwargs):
        res = None
        try:
            req = AddTagsToResourceRequest.AddTagsToResourceRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_Tags(kwargs["Tags"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute AddTagsToResource with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def DescribeTags(self, **kwargs):
        res = None
        try:
            req = DescribeTagsRequest.DescribeTagsRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_Tags(kwargs["Tags"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute DescribeTags with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res

    def RemoveTagsFromResource(self, **kwargs):
        res = None
        try:
            req = RemoveTagsFromResourceRequest.RemoveTagsFromResourceRequest()
            req.set_accept_format("json")

            req.set_DBInstanceId(kwargs["DBInstanceId"])
            req.set_Tags(kwargs["Tags"])

            res_str = self.clt.do_action_with_exception(req)
            res = json.loads(res_str)
            res["StatusCode"] = "200"
            res["Message"] = ""
        except Exception as ex:
            debug(traceback.format_exc())
            error("Failed to execute RemoveTagsFromResource with some exception %s." % (ex))
            res = {"StatusCode": "403", "Message": str(ex)}
            res["RequestId"] = _get_exception_response_id(res["Message"])

        return res
